<template>
  <basic-container :btnFlag=true>
    <div class="card-border">
      <card-header :header-data="headerData"></card-header>
      <el-form
        label-width="130px"
        :model="subjectForm"
        style="padding-right: 30px;"
        :rules="planOpinionRules"
        ref="subjectForm"
      >
        <el-row>
          <el-col :span="22" style="margin-top: 27px">
            <el-form-item class="form-item" label="计划名称 :" prop="titleTemp">
              {{titleTemp}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22" style="margin-top: 27px">
            <el-form-item class="form-item" label="征求主题 :" prop="title">
              <el-input v-model="subjectForm.title" placeholder="请输入征求主题"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="征求部门 :" prop="orgCode" class="form-item">
              <span style="font-size: 16px">{{notifyDeptNames}},{{subjectForm.deptName}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button size="small" type="primary" icon="el-icon-plus" style="margin-left: 10px;"
                       @click="clickjointassortEditDept">选择增加征求部门
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item class="form-item" label="征求说明 :" prop="content">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                v-model="subjectForm.content"
                placeholder="请输入有关说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="form-item" label="截止时间 :" prop="endDate">
              <el-date-picker
                style="width: 100%"
                v-model="subjectForm.endDate"
                type="date"
                placeholder="选择截止时间"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                :picker-options="expireTimeOption"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin-left: 14px;margin-bottom: -13px;font-weight: 600">
        <span>课题计划方案</span>
      </div>
      <div class="card-body">
        <avue-crud :data="subjectListData"
                   :option="tableoption"
                   :page="page"
                   :table-loading="tableLoading"
                   @on-load="getResultList"
                   @size-change="sizeChange"
                   @current-change="currentChange"
                   class="avuecrud">
          <template slot-scope="scope" slot="menu">
            <div class="menu-title" @click.stop="planFeedback(scope.row,scope.index)">
              <i class="iconfont iconview icon-primary"></i>
              <p class="menu-title-text">查看反馈</p>
            </div>
            <div class="menu-title" @click.stop="subjectOpinionDelete(scope.row,scope.index)">
              <i class="iconfont iconalter icon-warning"></i>
              <p class="menu-title-text">删除</p>
            </div>
          </template>
        </avue-crud>
      </div>
      <div slot="footer" class="btn-footer">
        <el-button type="success" @click="exportPlanFile()">导出方案</el-button>
        <el-button type="primary" @click="submitToOpinion()">发 送</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </div>
      <dept-check :visible="deptVisible" mini-type="2" @getCheckInfo="getCheckInfo" @cancel="cancelSupportDept"></dept-check>
    </div>
  </basic-container>
</template>

<script>
  import {getPlanSubjectList, addSubjectPlanOpinion, exportSubjectAssignDept} from "@/api/subject";
  import {filedownload} from "@/api/system";
  import {planOpinionRules} from "@/const/infoRules";
  import {mapGetters} from "vuex";
  export default {
    name: "planningForComments",
      computed: {
      ...mapGetters([
        "deptInfo"
      ])
    },
    created() {
      this.titleTemp = this.$route.query.title;
      this.subjectForm.title =this.deptInfo.name+'关于征求《'+this.$route.query.achievementTitle+'前期研究课题计划（征求意见稿）》意见的函';
      this.createTimeTemp = this.$route.query.createTime.split(' ')[0];
      this.putSubjectListData();
    },
    data() {
      return {
        headerData: {
          title: '课题计划-征求意见'
        },
        subjectListData: [],
        notifyDeptNames: "",
        planOpinionRules,
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        tableLoading: false,
        tableoption: {
          page: true,
          menuWidth: 220,
          addBtn: false,
          editBtn: false,
          addRowBtn: false,
          indexLabel: "序号",
          index: true,
          indexWidth:70,
          cellBtn: false,
          delBtn: false,
          columnBtn: false,
          refreshBtn: false,
          filterBtn: false,
          searchBtn: false,
          keyId: "id",
          menu: false,
          column: [
            {
              label: "课题名称",
              width: 250,
              prop: "title",
              cell: true
            },
            {
              label: "课题概述",
              width: 330,
              prop: "description",
              cell: true
            },
            {
              label: "拟牵头单位",
              prop: "deptName",
              cell: true,
            },
            {
              label: "拟配合单位",
              prop: "supportDeptName",
              cell: true,
            },
          ]
        },
        subjectForm: {
          title: '',
          content: '',
          planId: 0,
          endDate: '',
          deptIds: [],
          fileIds: [],
          deptName: '',
        },
        titleTemp: '',
        createTimeTemp: '',
        deptVisible: false,
        expireTimeOption: {
          disabledDate(date) { //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
            return date.getTime() <= Date.now();
          }
        },

      }
    },
    methods: {
      currentChange(currentPage) {
        var page = this.page;
        page.currentPage = currentPage;
        this.getResultListPage(page);
      },
      sizeChange(pageSize) {
        var page = this.page;
        page.pageSize = pageSize;
        this.getResultListPage(page);
      },
      getResultListPage(page) {
        getPlanSubjectList(Object.assign({
          current: page.currentPage,
          size: page.pageSize,
          planId: this.$route.params.id,
        })).then(response => {
          this.subjectListData = response.data.data.records;
          this.page.total = response.data.data.total;
        })
      },
      putSubjectListData(){
        getPlanSubjectList(Object.assign({
          current: 1,
          size: 10,
          planId: this.$route.params.id,
        })).then(response => {
          this.subjectListData = response.data.data.records;
          this.page.total = response.data.data.total;
          let notifyDeptNameSet = new Set();
          //遍历出有的配合部门和征求部门
          for (let subject of this.subjectListData) {
            notifyDeptNameSet.add(subject.deptName);
            notifyDeptNameSet.add(subject.supportDeptName);
          }
          this.notifyDeptNames = [...notifyDeptNameSet].join(",")
        })
      },
      getResultList() {

      },
      // 弹出协同部门弹框
      clickjointassortEditDept() {
        this.deptVisible = true
      },
      cancelSupportDept(deptIds, deptNames) {
        this.deptVisible = false;
      },
      getCheckInfo(deptIds, deptNames) {
        this.subjectForm.deptName = deptNames;
        this.subjectForm.deptIds = deptIds.split(",");
        this.deptVisible = false;
      },
      cancel() {
        this.$router.go(-1)
      },
      submitToOpinion() {
        this.$refs.subjectForm.validate(valid => {
          if (valid) {
            this.$confirm("确定征求意见吗?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.subjectForm.planId = this.$route.params.id;
              addSubjectPlanOpinion(this.subjectForm).then(response => {
                if (response.data.code == 0) {
                  this.$notify({
                    title: '成功',
                    message: '征求意见发送成功',
                    type: 'success',
                    duration: 2000
                  });
                  this.$router.go(-1)
                }
              })
            })
          }
        })
      },
      exportPlanFile() {
        this.$confirm("确定要导出方案吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          exportSubjectAssignDept(this.$route.params.id).then(response => {
            var exportFileName = this.$route.query.achievementTitle + "课题计划方案.docx";
            this.download(response.data, exportFileName)
          });
        })
      },
      // 附件下载
      downloadFile(fileId, fileName) {
        filedownload(fileId).then(response => {
          if (response.status == 200) {
            this.download(response.data, fileName)
          }
        }).catch((error) => {
          this.$notify({
            title: "失败",
            message: "上传失败[" + error + "]",
            type: "error",
            duration: 2000
          });
        })
      },
      // 下载文件
      download(data, filename) {
        if (data == null) {

        } else {
          let url = window.URL.createObjectURL(new Blob([data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', filename);
          document.body.appendChild(link);
          link.click()
        }
      },
    }

  }
</script>

<style lang="scss" scoped>
  .btn-footer {
    text-align: center;
    margin-bottom: 20px;
  }
</style>

